<template>
  <div class="wrapper">
    <!-- 普通文件上传（有文件列表） -->
    <template v-if="uploadType == 'list'">
      <div class="uploadWrap">
        <div v-for="(item, index) in uploadLists" :key="index" class="uploadName">
          <a-popover
            :key="item.fileId"
            placement="top"
          >
            <template slot="content">
              <a
                :fileId="item.fileId"
                :fileName="item.fileName"
                :href="'/api/ycloud-file-center/oper/download?access_token=' + token + '&fileId=' + item.fileId"
                target="_parent"
              >下载</a>
              <a-divider type="vertical" />
              <a
                :key="item.fileId"
                @click="$filePreview(item)"
              >查看</a>
            </template>
            <a :href="'/api/ycloud-file-center/oper/download?access_token=' + token + '&fileId=' + item.fileId" target="_parent">{{ item.fileName }}</a>
          </a-popover>
          <img v-if="isClose && typePage != 'view' && typePage != 'approve'" style="cursor: pointer" src="../../../assets/delete.png" width="30" height="30" @click="deleteFiles(item)" />
        </div>
      </div>
      <div>
        <a-upload v-if="showUpload" v-bind="$attrs" name="file" :multiple="true" :show-upload-list="false" :before-upload="beforeUpload" @change="handleUpload" :disabled="typePage == 'view'" v-on="$listeners">
          <a-button v-if="typePage != 'view'" :loading="loadingState.isUpload" @click="infoArr = []">
            <a-icon type="upload" style="color: #1890ff" />
            {{ text }}
          </a-button>
        </a-upload>
      </div>
    </template>
  </div>
</template>

<script>
import Vue from 'vue'
import { uploadFile, deleteFile } from '@/api'
import { uploadFiles, uploadFiles1, uploadFiles2, deleteFiles, deleteFiles1,deleteFiles2 } from '@/api/construction/planInput'
import { Item } from 'ant-design-vue/es/vc-menu'
import debounce from 'lodash/debounce'
const columnAssment = [
  {
    title: '序号',
    dataIndex: 'serial',
    width: '10%',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '附件名称',
    dataIndex: 'fileName',
    width: '15%'
  },
  {
    title: '附件格式',
    dataIndex: 'suffixName',
    width: '15%'
  },
  {
    title: '附件地址',
    dataIndex: 'rootPath',
    width: '40%'
  },
  {
    title: '操作',
    key: 'action',
    width: '20%',
    scopedSlots: { customRender: 'action' }
  }
]
// 转化base64
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject(error)
  })
}
export default {
  name: 'UploadList',
  inheritAttrs: false,
  components: {},
  props: {
    projectId: {
      type: String
    },
    // type:{
    //   type:String
    // },
    // 文件类型
    uploadType: {
      type: String,
      default() {
        return 'list'
      }
    },
    btnType: {
      type: String,
      default() {
        return 'upload'
      }
    },
    // 上传按钮名称
    text: {
      type: String,
      default() {
        return '上传文件'
      }
    },
    // 图片可上传数量
    count: {
      type: [String, Number],
      default() {
        return 100
      }
    },
    // 图片文件类型
    accept: {
      type: String,
      default() {
        return ''
      }
    },
    // 上传图片操作模式 0 查看；1 编辑；2 添加
    editModel: {
      type: [String, Number],
      default() {
        return '0'
      }
    },
    // 是否禁止编辑
    disabled: {
      type: Boolean,
      default() {
        return true
      }
    },
    // 业务编码
    businessCode: {
      type: String,
      value: ''
    },
    listUpload: {
      type: String,
      value: ''
    },
    businessId: {
      type: String,
      value: ''
    },
    uploadList: {
      type: String,
      value: ''
    },
    // 文件列表
    uploadArrys: {
      type: Array,
      default: () => []
    },
    // 是否自定义按钮
    customBtn: {
      type: Boolean,
      default: () => false
    },
    // 是否显示删除图标和上传按钮
    showUpload: {
      type: Boolean,
      default: () => true
    },
    isClose: {
      type: Boolean,
      default: () => true
    },
    updateCode: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      columnAssment,
      uploadFileObj: {},
      uploadLists: [],
      deleteObj: {},
      token: '',
      typePage: '',
      previewVisible: false, // 预览控件
      previewImage: '', // 预览图
      loadingState: {
        isUpload: false
      },
      infoArr: [], //文件信息
      total: 0 ,//总数,
    }
  },
  created() {
    this.typePage = this.$route.query.pageType === 'detail' ? 'view' : this.$route.query.type
    this.token = Vue.getAcloudProvider().getAccessToken()
    this.initUploadList()
  },
  computed: {
    imgList: {
      get: function () {
        return this.uploadArrys
      },
      set: function (val) {
        this.$emit('update:uploadArrys', val)
      }
    }
  },
  watch: {
    uploadArrys() {
      this.initUploadList()
    },
    showUpload: {
      handler(newName, oldName) {
        this.showUpload = newName
      }
    }
  },
  methods: {
    initUploadList() {
      if (this.uploadArrys && this.uploadArrys.length != 0) {
        this.uploadLists =
          this.uploadType == 'image'
            ? this.uploadArrys.map((item) => {
                const { id, fileName, fileId } = item
                if (id) {
                  return {
                    ...item,
                    name: fileName,
                    uid: id,
                    url: '/api/ycloud-file-center/oper/download?access_token=' + this.token + '&fileId=' + fileId
                  }
                }
                return item
              })
            : this.uploadArrys
      }
      this.total = this.uploadLists.length
    },
    beforeUpload(info) {
      return false
    },
    handleCancel() {
      this.previewVisible = false
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    /**
     * @description: 提示防抖
     * @param {void}
     * @return {function}
     */
    numMesgDebounce: debounce(function () {
      this.$message.error(`一次最多上传5个文件！`)
      this.infoArr = this.infoArr.slice(0, (5 - this.total));
    }, 500),
    /**
     * 上传
     * @param {Object} options - 配置对象
     */
    async handleUpload(options) {
      const { size, name } = options.file
      if (size / 1024 / 1024 > 20) {
        this.$message.warning('上传文件不可超出20M')
        return false
      }
      if (this.needChineseName) {
        let re = new RegExp('[\\u4E00-\\u9FFF]+', 'g')
        if (!re.test(name)) {
          this.$confirm({
            title: '提示',
            content: '请规范附件名称，附件名称中需含有汉字',
            okType: 'danger'
          })
          return false
        }
      }
      try {
        this.infoArr.push(options.file)
        if ((this.total + this.infoArr.length) > 5) {
          this.numMesgDebounce()
          return
        }
        this.fileChange()
      } catch (e) {
        console.error(e)
        // options.onError() // 调用回调，避免一直loading
      }
      this.loadingState.isUpload = false
    },
    /**
     * @description: 文件上传防抖
     * @param {function}
     * @return {void}
     */
    fileChange: debounce(function () {
      this.uploadFnChange()
    }, 500),
    /**
     * @description: 文件上传前置条件
     * @param {function}
     * @return {void}
     */
    async uploadFnChange() {
      let that = this
      for (let index = 0; index < that.infoArr.length; index++) {
        await that.uploadFn(that.infoArr[index])
      }
    },
    /**
     * @description: 文件上传
     * @param {function}
     * @return {void}
     */
    async uploadFn(info) {
      let that = this
      if (!info) return
      const data = new FormData()
      data.append('file', info)
      data.append('businessCode', that.businessCode)
      if (that.infoArr.length < that.uploadLists.length && that.uploadType == 'image') {
        that.uploadLists = that.infoArr
        return
      }
      // 上传
      let res = await uploadFile(data)
      //  .then((res) => {
      if (res.code === 200) {
        that.uploadLists.push(res.data)
        switch (that.updateCode) {
          case 0: {
            uploadFiles({ commonFileId: res.data.commonId, businessId: that.projectId })
            break
          }
          case 1: {
            uploadFiles1({ commonFileId: res.data.commonId, businessId: that.projectId })
            break
          }
          case 2: {
            uploadFiles2({ commonFileId: res.data.commonId, businessId: that.projectId })
            break
          }
        }
      }
      if (that.uploadLists.length > 10) {
        that.$emit('update:showUpload', false)
      }
      that.$emit('fileArrysData', that.uploadLists)
      that.$emit('update:uploadArrys', that.uploadLists)
      // })
    },
    // 删除文件
    async deleteFiles(record) {
      let that = this
      let arr = []

      let commonId = record.originFileObj && record.originFileObj.commonId ? record.originFileObj.commonId : record.commonId
      // arr.push({businessId:this.projectId,commonId:commonId})
      let res = void 0
      switch (this.updateCode) {
        case 0: {
          res = await deleteFiles({ businessId: that.projectId, commonFileId: commonId })
          break
        }
        case 1: {
          res = await deleteFiles1({ businessId: that.projectId, commonFileId: commonId })
          break
        }
        case 2: {
          res = await deleteFiles2({ businessId: that.projectId, commonFileId: commonId })
          break
        }
      }
      if (res.data.code == 200) {
        // if (this.uploadType == 'image') {
        //   this.imgList.forEach((obj, i) => {
        //     console.log(obj.commonId, commonId)
        //     if (obj.commonId == commonId) {
        //       this.imgList.splice(i, 1)
        //     }
        //   })
        // } else {
        that.uploadLists.forEach((obj, i) => {
          // console.log(obj, commonId)
          if (obj.commonId == commonId) {
            that.uploadLists.splice(i, 1)
            this.infoArr.splice(i, 1)
          }
        })
        // }
      }
      this.total = that.uploadLists.length;
      if (that.uploadLists.length > 5) {
        that.$emit('update:showUpload', true)
        // }
      }
      that.$emit('fileArrysData', that.uploadLists)
      that.$emit('update:uploadArrys', that.uploadLists)
    }
  }
}
</script>

<style scoped>
.wrapper {
  overflow: hidden;
}
.uploadWrap {
  float: left;
}
.uploadName {
  float: left;
  margin-right: 20px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>